package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDTO;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author jiang zhongxun
 * @create 2023-03-06 22:02
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    CourseBaseMapper courseBaseMapper;
    @Resource
    CourseMarketMapper courseMarketMapper;
    @Resource
    CourseCategoryMapper courseCategoryMapper;

    /**
     * 查询课程信息
     *
     * @param pageParams           页面参数
     * @param queryCourseParamsDTO 查询课程params dto
     * @return {@link PageResult}<{@link CourseBase}>
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDTO queryCourseParamsDTO) {
        /* 查询条件 */
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDTO.getCourseName()), CourseBase::getName, queryCourseParamsDTO.getCourseName());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDTO.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDTO.getAuditStatus());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDTO.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDTO.getPublishStatus());
        /* 分页参数 */
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        /* 查询数据 */
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        List<CourseBase> items = pageResult.getRecords();
        long counts = pageResult.getTotal();
        /* 封装数据并返回 */
        return new PageResult<>(items, counts, pageParams.getPageNo(), pageParams.getPageSize());
    }

    /**
     * 新增课程信息
     * @param companyId    公司标识ID
     * @param addCourseDto 添加课程dto
     * @return {@link CourseBaseInfoDto} 返回添加的课程详细信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        /* 向课程基本信息 course_base 表写入数据 */
        CourseBase courseBaseNew = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBaseNew);
        courseBaseNew.setCompanyId(companyId);
        courseBaseNew.setCreateDate(LocalDateTime.now());
        /* 审核状态、发布状态默认为未提交、未发布 */
        courseBaseNew.setAuditStatus("202002");
        courseBaseNew.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBaseNew);
        if (insert <= 0) {
            XueChengPlusException.cast("课程添加失败");
        }
        /* 向课程营销表 course_market 表写入数据 */
        CourseMarket courseMarketNew = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarketNew);
        courseMarketNew.setId(courseBaseNew.getId());
        int result = saveCourseMarket(courseMarketNew);
        if (result <= 0) {
            XueChengPlusException.cast("课程添加/更新失败");
        }
        /* 从数据库查出详细的课程信息 */
        return getCourseBaseInfo(courseBaseNew.getId());
    }

    /**
     * 查询课程信息
     *
     * @param courseId 课程id
     * @return {@link CourseBaseInfoDto}
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        /* 查询课程基本信息表 */
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        /* 查询课程营销信息表 */
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        /* 封装要返回的数据 */
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        /* 查询课程分类信息，设置课程分类名称 */
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());
        return courseBaseInfoDto;
    }

    /**
     * 修改课程基础
     *
     * @param companyId     公司标识ID
     * @param editCourseDto 编辑课程dto
     * @return {@link CourseBaseInfoDto}
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        Long courseId = editCourseDto.getCourseId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        /* 数据操作校验 */
        if (courseBase == null) {
            XueChengPlusException.cast("要修改的课程不存在！");
        }
        if (!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("本机构只能修改自己的课程！");
        }
        /* 封装数据，执行更新 */
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int update = courseBaseMapper.updateById(courseBase);
        if (update <= 0) {
            XueChengPlusException.cast("课程修改失败！");
        }
        /* 更新营销信息 */
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        int result = saveCourseMarket(courseMarket);
        if (result <= 0) {
            XueChengPlusException.cast("课程更新失败");
        }
        /* 查询最新数据并返回 */
        return getCourseBaseInfo(courseId);
    }

    /**
     * 单独定义一个方法保存营销信息
     * 逻辑：存在则更新，不存在则添加
     *
     * @param courseMarketNew 课程营销信息
     * @return int
     */
    private int saveCourseMarket(CourseMarket courseMarketNew) {
        int result;
        /* 如果课程收费，则价格为必填 */
        if ("201001".equals(courseMarketNew.getCharge())) {
            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice() <= 0) {
                XueChengPlusException.cast("课程价格不能为空，并且必须大于0");
            }
        }
        /* 从数据库查询课程营销信息，存在则更新，不存在则添加 */
        CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());
        if (courseMarket == null) {
            // 添加
            result = courseMarketMapper.insert(courseMarketNew);
        } else {
            // 更新
            BeanUtils.copyProperties(courseMarketNew, courseMarket);
            courseMarket.setId(courseMarketNew.getId());
            result = courseMarketMapper.updateById(courseMarket);
        }
        return result;
    }

}
